import React, { Component } from 'react';
import {
	StyleSheet, Text, View, Image, NativeModules, Platform, TouchableOpacity, DeviceEventEmitter, PixelRatio,
	ActivityIndicator, ListView
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { PoiSearch } from 'react-native-baidu-map';
import { SearchInput } from '../../../component/SearchInput';

const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
const scale = GLOBAL.SCALE;
const searchLeft = require('../../../imgs/customer/searchLeft.png');
const addressSide = require('../../../imgs/customer/addressSide.png');
const addressSideCur = require('../../../imgs/customer/addressSideCur.png');
const arrowLeft = require('../../../imgs/arrow-left.png');
const emptyPic = require('../../../imgs/global/dealtWithEmpty.png');
let addressdefault = {};

const requestObj = {
	keyword: "",
	pageSize: 10,
};
let curCityStr = '';
export class AddressListPage extends Component {

	static navigationOptions = ({ navigation }) => {
		const params = navigation.state.params || {};
		const { curCity, curAddress, citySelected } = params;
		if (curCity && curCity.length) {
			curCityStr = curCity;
		}
		if (citySelected && citySelected.length) {
			console.log(70, curCity, curAddress, citySelected);
			curCityStr = citySelected;
		}

		if (curAddress && curAddress.length) {
			curAdressName = curAddress;
		}

		return {
			headerTintColor: '#404040',
			headerTitle: <SearchInput setKeyWord={(txt) => { params.setKeyWord(txt); }}
				onChangeText={() => { params.doSearch(); }}
				onSubmitEditing={() => { params.doSearch(); }}
				placeholder='搜索地区'
				inputLeftIcon={searchLeft}
				inputViewStyle={{ marginLeft: 15 * scale }} />,
			headerRight: (
				<Text style={{ marginRight: 10 * scale, fontSize: 12 * scale, color: '#404040' }} onPress={() => { navigation.goBack() }}>取消</Text>
			),
			headerLeft: <TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', paddingLeft: 15 * scale, }} onPress={() => {
				const { navigate } = navigation;
				navigate('AreaListPage', {
					curCity: params.curCity
				});
			}} activeOpacity={0.5}>
				<Text >{curCityStr ? curCityStr.substring(0, 2) : '城市'}</Text>
				<Image source={arrowLeft} style={styles.arrowLeft} />
			</TouchableOpacity>,
			headerStyle: {
				elevation: 0,
				borderBottomWidth: 1,
				borderBottomColor: '#E4E4E4',
				backgroundColor: '#fff',
			},
		};
	}
	/**
 * 设置搜索关键字
 * @param {String} txt 
 */
	_setKeyWord (txt) {
		requestObj.keyword = txt;
	}

	_doSearch () {
		if (NativeModules.BaiduPoiSearchModule) {
			console.log('_doSearch', curCityStr, requestObj.keyword);
			PoiSearch.getSuggestionSearchPoi(curCityStr, requestObj.keyword).then(
				(data) => {
					if (data.length) {
						const responseData = data;

						if (responseData && responseData.length && (responseData.length < 11)) {
							const l = responseData.unshift(addressdefault);
							console.log("l");
							console.log(l);
						}

						this.setState({
							dataSource: ds.cloneWithRows(responseData),
							emptyResult: false,
						});
					} else {
						this.setState({
							dataSource: ds.cloneWithRows([]),
							emptyResult: true,
						});
					}
				}
			).catch(error => {
				console.log(107)
				console.warn(error, 'error')
			})
		} else {
			console.log(109);
			// this.setState({
			// 	dataSource: ds.cloneWithRows(
			// 		[{ "longitude": 121.42141355930694, "latitude": 31.22263590585235, "city": "上海市", "district": "长宁区", "key": "长宁来福士" }, { "longitude": 121.43045051273731, "latitude": 31.226843336296152, "city": "上海市", "district": "长宁区", "key": "长宁区" }, { "longitude": 121.42096440655193, "latitude": 31.219208061232912, "city": "上海市", "district": "长宁区", "key": "上海市长宁区妇幼保健院" }, { "longitude": 121.43248966624496, "latitude": 31.234192375659234, "city": "上海市", "district": "长宁区", "key": "长宁八八中心" }, { "longitude": 121.42321915338198, "latitude": 31.22532250712117, "city": "上海市", "district": "长宁区", "key": "龙之梦购物公园" }, { "longitude": 121.38256184600039, "latitude": 31.214120105474066, "city": "上海市", "district": "长宁区", "key": "长宁区中心医院-西门" }, { "longitude": 121.41980559244406, "latitude": 31.221995124619042, "city": "上海市", "district": "长宁区", "key": "长宁来福士广场-停车场" }, { "longitude": 121.39512914008498, "latitude": 31.220590022702822, "city": "上海市", "district": "长宁区", "key": "长宁图书馆" }, { "longitude": 121.41622135345925, "latitude": 31.203287011620557, "city": "上海市", "district": "长宁区", "key": "上海市长宁区人民法院" }, { "longitude": 121.37287811260282, "latitude": 31.207178730550222, "city": "上海市", "district": "长宁区", "key": "长宁区车管所" }]
			// 	),
			// });
		}

	}

	_doCancel () {

	}

	constructor(props) {
		super(props);
		this.state = {
			loaded: false,
			emptyResult: false,
			dataSource: ds.cloneWithRows([]),
			// showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
		}

		this._setKeyWord = this._setKeyWord.bind(this);
		this._doCancel = this._doCancel.bind(this);
		this._doSearch = this._doSearch.bind(this);
		this.renderAddress = this.renderAddress.bind(this);

	}

	async componentDidMount () {
		requestObj.companyName = '';
		this.props.navigation.setParams({
			doCancel: this._doCancel,
			setKeyWord: this._setKeyWord,
			doSearch: this._doSearch
		});
		const { curCity, curAddress, addressObj } = this.props.navigation.state.params;
		addressdefault = addressObj;
		addressdefault.isDefault = true;
		console.log(174, addressdefault);

		if (curAddress) {
			requestObj.keyword = curAddress;
			curCityStr = curCity
		} else {
			requestObj.keyword = '';
			curCityStr = '';
		}

		this._doSearch();
	}
	componentWillUnmount () {
		DeviceEventEmitter.emit('CheckAddressItem');
	}
	//加载等待页
	renderLoadingView () {
		return (
			<View style={styles.container}>
				<View style={styles.loadedCell}>
					<ActivityIndicator
						animating={true}
						color={'#fff'}
						size="small"
					/>
				</View>
			</View>
		);
	}

	render () {
		console.log(this.state.dataSource)
		if (this.state.loaded) {
			//数据加载未完成
			return this.renderLoadingView();
		} else {
			const emptyResult = this.state.emptyResult ?
				<View style={styles.panelEmptyView}>
					<Image source={emptyPic} style={styles.emptyPic} />
					<Text style={styles.emptyText}>没有查询到满足条件的地址</Text>
				</View> : null;
			return (
				<View style={{ flex: 1, backgroundColor: '#fff' }}>
					{emptyResult}
					<ListView
						dataSource={this.state.dataSource}
						renderRow={this.renderAddress}
						style={styles.listView}
					/>
				</View>
			);
		}
	}

	//{"name":"虹桥","longitude":"121.158838","latitude":"31.204504","city":"上海市","address":"上海市青浦区"}
	renderAddress (item) {
		const { address, name, key, isDefault } = item;
		const source = (isDefault) ? addressSideCur : addressSide;
		let nameText = <Text style={styles.resultText}>{name}</Text>;
		if (Platform.OS === 'android') {
			item.name = key;
			nameText = <Text style={styles.resultText}>{key}</Text>
		}

		return (
			<TouchableOpacity style={styles.resultRow} onPress={() => {
				const { navigate } = this.props.navigation;
				navigate('AddressOptionPage', {
					selectAddress: item,
					goBackPage: 'AddressListPage'
				});
			}} activeOpacity={0.5}>
				<View style={styles.resultRowLeft}>
					<Image source={source} style={styles.addressSide} />
				</View>
				<View style={styles.resultRowRight}>
					{nameText}
					<Text style={[styles.resultText, styles.resultGrayText]}>{address}</Text>
				</View>
			</TouchableOpacity>
		);
	}

}

const styles = StyleSheet.create({
	arrowLeft: {
		width: 6 * scale,
		height: 8 * scale,
		marginLeft: 10 * scale,
		transform: [{ rotateZ: '90deg' }]
	},
	addressSide: {
		height: 28 * scale,
		width: 28 * scale,
	},
	headerLeft: {
		fontSize: 14 * scale,
		color: '#404040'
	},
	resultRow: {
		flexDirection: 'row',
		paddingTop: 17 * scale,
		width: 375 * scale,
	},
	resultRowLeft: {
		height: 40 * scale,
		width: 64 * scale,
		justifyContent: 'center',
		alignItems: 'center',
	},
	resultRowRight: {
		flex: 1,
		borderBottomColor: '#e4e4e4',
		borderBottomWidth: 1 / PixelRatio.get(),
		justifyContent: 'center',
	},
	resultText: {
		fontSize: 13 * scale,
		color: '#404040'
	},
	resultGrayText: {
		color: '#8B8B8B'
	},
	panelEmptyView: {
		height: 375 * scale,
		justifyContent: 'center',
		alignItems: 'center',
		width: 375 * scale,
	},
	emptyPic: {
		width: 143 * scale,
		height: 120 * scale,
	},
	emptyText: {
		marginTop: 16 * scale,
		marginBottom: 60 * scale,
		fontSize: 13 * scale,
		color: '#4B4B4B'
	},
	container: {
		flex: 1,
		backgroundColor: '#fff',
		justifyContent: 'center',
		alignItems: 'center',
	},
	limitView: {
		width: 18 * scale,
		height: 13 * scale,
		marginLeft: 4 * scale,
		justifyContent: 'center',
		alignItems: 'center',
		backgroundColor: style.color.themeColor,
	},
	limitText: {
		fontSize: 10 * scale,
		color: '#fff'
	},
	listView: {
		backgroundColor: '#fff',
	},
	loadedCell: {
		width: 75 * scale,
		height: 75 * scale,
		backgroundColor: 'rgba(0, 0, 0, .5)',
		borderRadius: 7,
		justifyContent: 'center',
		alignItems: 'center',
	},
	customerRow: {
		borderBottomColor: '#e4e4e4',
		borderBottomWidth: 1 / PixelRatio.get(),
		width: 375 * scale,
		paddingTop: 12 * scale,
		paddingBottom: 16 * scale,
		paddingLeft: 16 * scale,
		paddingRight: 14 * scale,
		height: 72 * scale,
		flexDirection: 'row'
	},
	classificationView: {
		flex: 1,
	},
	classificationImg: {
		width: 44 * scale,
		height: 44 * scale,
		resizeMode: 'contain'
	},
	infoView: {
		flex: 4,
		justifyContent: 'space-between',
	},
	dateView: {
		flex: 2,
		alignItems: 'flex-end',
	},
	customerNameText: {
		fontSize: 14 * scale,
		color: '#4B4B4B',
	},
	explainText: {
		fontSize: 12 * scale,
		color: '#8B8B8B',
	},
})